package com.smart.home.util;

/**
 * 命令解码
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-09
 */
public abstract class CommandDecoder {

    /**
     * 解析有线输入按钮名字
     *
     * @param code 设备查询返回码
     * @return
     */
    public static String wireButtonNameDecoder(String code) {
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        String nameCode = code.substring(6, code.length() - 2);
        return hexToStringGBK(nameCode);
    }

    /**
     * 16进制转GBK字符串
     *
     * @param s 16字符串
     * @return
     */
    public static String hexToStringGBK(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
        try {
            s = new String(baKeyword, "GBK");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
            return "";
        }
        return s;
    }

    public static String hexToString(byte[] hexArray){
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < hexArray.length; i++) {
            stringBuilder.append(hexArray[i]);
        }
        return stringBuilder.toString();
    }


    /**
     * 16进制字符串转换为字符串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

}
